import { setToken, getToken, removeToken } from '@/utils/auth'
import { login } from '@/api/user'
import { Message } from 'element-ui'
import router from '@/router'

const state = {
  token: getToken()
}
const getters = {}
const mutations = {
  setToken(state, token) {
    state.token = token
    setToken(token)
    router.push('/')
  },
  removeToken(state) {
    state.token = null
    removeToken()
    router.push('/login')
  }
}
const actions = {
  async login(store, data) {
    const { msg, token } = await login(data)
    if (token) {
      Message.success(msg)
      store.commit('setToken', token)
    } else Message.error(msg)
  },
  async logout(store) {
    Message.success('成功登出')
    store.commit('removeToken')
  }
}
export default {
  namespaced: true,
  state,
  getters,
  mutations,
  actions
}
